﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using System.Web.Routing;
using System.Security.Principal;
using agent02.Model;

namespace agent02.Areas.Admin.Filter
{
    public class AdminAuthorize : ActionFilterAttribute
    {
        AgentDBEntities db = new AgentDBEntities();

        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            // get current logged in user
            IPrincipal user = HttpContext.Current.User;
            string username = user.Identity.Name;

            // get user's id
            var u = from t in db.TAI_KHOAN
                          where t.Username == username
                          select t;
            if (u.Count() == 1)
            {
                string u_id = (from t in db.TAI_KHOAN
                               where t.Username == username
                               select t).Single().MaTaiKhoan;

                // get a list of user's groups
                var group = (from g in db.TAIKHOAN_NHOM
                             join n in db.NHOM
                             on g.Nhom equals n.ID
                             where g.TaiKhoan == u_id
                             select n.TenNhom).ToList();

                // if user does not belong to group admin, kick out
                if (!group.Contains("admin"))
                {
                    // redirect
                    var routeValues = new RouteValueDictionary()
                    {
                        { "controller", "Home" },
                        { "action", "AccessDenied" },
                        { "area", "" }
                    };

                    filterContext.Result = new RedirectToRouteResult(routeValues);
                }
            }
            else
            {
                // redirect to log on page
                var routeValues = new RouteValueDictionary()
                    {
                        { "controller", "Account" },
                        { "action", "LogOn" },
                        { "area", "" }
                    };

                filterContext.Result = new RedirectToRouteResult(routeValues);
            }
        }
    }
}